import React from 'react';
import PropTypes from 'prop-types';
import { stripesConnect } from '@folio/stripes/core';
import { FormattedMessage, injectIntl } from 'react-intl';
import AddAppointment from './cake-hub';

class CakeBackKitchen extends React.Component {
  static manifest = Object.freeze({
    httpInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/reserve'
    },
    findHttpInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/reserve',
      Get: {
        params: {
          query: '(isDel = 0 ${query})'
        }
      }
    },
    findUserHttpInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/users',
      params: {
        query: ''
      }
    }
  });

  static propTypes = {
    mutator: PropTypes.shape({
      httpInvoke: PropTypes.shape({
        PUT: PropTypes.func.isRequired,
        POST: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired
      }),
      activityMessageGetAllInvoke: PropTypes.shape({
        GET: PropTypes.func.isRequired
      }),
      findUserhttpInvoke: PropTypes.shape({
        GET: PropTypes.func.isRequired
      })
    }).isRequired
  };

  constructor(props) {
    super(props);
    this.state = {
      data: {},
      message:  <FormattedMessage id={"ui-party.other.submitting"}/>,
      open: false,
      promptFlag: true,
      operator: {}
    };
  }

  componentDidMount() {
    const { currentUser } = this.props.okapi;
    if (currentUser) {
      this.setState({
        operator: currentUser
      });
    }
  }

  static propTypes = {
    handleSubmit: PropTypes.func.isRequired,
    initialValues: PropTypes.object,
    dictionary: PropTypes.object,
    cleanSearch: PropTypes.func,
    intl: PropTypes.func
  };

  commit = ({ requestPreferences, creds, ...formData }) => {
    const {
      intl,
      mutator,
      history
    } = this.props;
    const { POST } = this.props.mutator.httpInvoke;
    const requestParams = {};
    const _this = this;
    this.setState({
      open: true
    });
    if (JSON.stringify(formData) === '{}') {
      requestParams.quotaFlag = false;
    } else {
      requestParams.quotaFlag = true;
    }

    if (JSON.stringify(this.state.data) !== '{}') {
      const data = this.state.data;
      const userdata = data.userdata;
      const actData = data.actData;

      if (!!userdata && !!actData) {
        const readerReserveGroup = [];
        userdata.forEach((a, b) => {
          const barcode = a.barcode;
          const name = a.username;
          const personal = a.personal;
          let mobilePhone = '';
          if (personal) {
            mobilePhone = personal.mobilePhone;
          }
          const temp = {
            barcode,
            name,
            mobilePhone
          };
          readerReserveGroup.push(temp);
        });

        const params = {
          channel: 1,
          partyId: actData.id,
          status: 1,
          quotaFlag: requestParams.quotaFlag,
          readerReserveGroup,
          propertyName: actData.propertyName,
          imageId: actData.imageId,
          partyVenue: actData.venue,
          partyStartDate: actData.partyStartDate,
          partyEndDate: actData.partyEndDate,
          partyCategory: actData.category,
          notes: '正常审核',
          partyName: actData.partyName,
          operator: this.state.operator
        };
        delete params.operator.addresses;
        delete params.operator.preferredContactTypeId;
        delete params.operator.servicePoints;
        delete params.operator.curServicePoint;
        delete params.operator.dateOfBirth;
        POST(params)
          .then(res => {
            alert(intl.formatMessage({id:"ui-party.other.saved.successfully"}));
            _this.cancel(false);
          })
          .catch(e => {
            console.log(e);
          });
      } else  {
        alert(intl.formatMessage({id:"ui-party.other.please.continue.to.fill.in.the.content"}));
        return false;
      }
    } else  {
      alert(intl.formatMessage({id:"ui-party.other.please.continue.to.fill.in.the.content"}));
      return false;
    }
  };

  activityDataAndUserData = data => {
    this.setState({ data });
  };

  cancel = (flag = true) => {
    const { removeTopMenu, matchPath } = this.props;
    removeTopMenu(matchPath, flag);
  };

  render() {
    return (
      <AddAppointment
        onSubmit={this.commit}
        shippingData={this.activityDataAndUserData}
        cancel={this.cancel}
        {...this.props}
        promptFlag={this.state.promptFlag}
      />
    );
  }
}

CakeBackKitchen.propTypes = {};

export default injectIntl(stripesConnect(CakeBackKitchen));
